<template>
  <div class="page_space btn_space">
    <p class="title_1">基本信息</p>
    <input-card>
      <inputItem
        v-model="params.assetCode"
        :content="params.assetCode"
        title="资产编号（选填）"
        tip="请输入资产编号"
        type="input"
      />
      <inputItem
        v-model="params.code"
        :content="params.code"
        title="出厂编号"
        tip="请输入出厂编号"
        type="input"
      />
      <inputItem
        v-model="params.name"
        :content="params.name"
        title="设备名称"
        tip="请输入设备名称"
        type="input"
      />
      <inputItem
        v-model="params.brand"
        :content="params.brand"
        title="品牌/厂家"
        tip="请输入品牌/厂家"
        type="input"
      />
      <inputItem
        v-model="params.allAreaName"
        :content="params.allAreaName"
        title="所属区划"
        tip="请选择所属区划"
        type="select"
        @select="toSelect(0)"
      />
      <inputItem
        v-model="params.typeText"
        :content="params.typeText"
        title="设备类型"
        tip="请选择设备类型"
        type="select"
        @select="toSelect(1)"
      />
      <inputItem
        title="生产日期（选填）"
        tip="请选择生产日期"
        type="select"
        :content="params.productDate"
        @select="toSelect(4)"
      />
      <input-item-textarea
        v-model="params.description"
        title="备注（选填）"
        tip="请输入备注"
      />
    </input-card>

    <div class="btn_wrap">
      <button v-debounce class="btn" @click="submit">提交</button>
    </div>

    <van-popup v-model="show" position="bottom" :round="true">
      <!-- 选择产地-->
      <template v-if="active === 0">
        <van-cascader
          v-model="cascaderValue"
          title=""
          :options="places"
          @close="show = false"
          @change="onChange"
          @finish="onFinish"
        />
      </template>
      <template v-if="active === 1">
        <van-picker
          ref="pickerForType"
          title="请选择设备类型"
          show-toolbar
          :columns="typeList"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="confirmType">确定</button>
        </div>
      </template>
      <template v-if="active === 4">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择年月日"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="submitTime">确定</button>
        </div>
      </template>
    </van-popup>
  </div>
</template>

<script>
import inputCard from '@/components/input-card/card'
import inputItem from '@/components/input-card/item'
import { getAreaList, getDepartment } from '@/api/base'
import { saveOrUpdateEquipment, getEquipmentDetail } from '@/api/person'
import { ParseDate } from '@/utils'
import inputItemTextarea from '@/components/input-card/item-textarea'

export default {
  name: 'addPerson',
  components: { inputCard, inputItem, inputItemTextarea },
  data() {
    return {
      show: false,
      active: 0,
      // 区划 区码
      cascaderValue: '',
      // 产地选项
      places: [],
      typeList: [
        { text: '台式', value: 'IN_TABLE' },
        { text: '手持', value: 'IN_HAND' }
      ],
      // 时间picker
      currentDate: new Date(),
      targetTime: {
        index: '',
        type: ''
      },

      params: {
        assetCode: '',
        code: '',
        name: '',
        brand: '',
        areaCode: '',
        allAreaName: '',
        type: '', // IN_TABLE
        typeText: '',
        productDate: '',
        description: ''
      },
      pageType: 'save'
    }
  },
  created() {
    const { id, type } = this.$route.query
    console.log(id, type)
    if (type === 'update' && id) {
      this.getEquipmentDetail(id)
      this.pageType = 'update'
    }
  },
  methods: {
    // 更新时 获取详情
    async getEquipmentDetail(id) {
      const { code, data } = await getEquipmentDetail(id)
      if (code === '0') {
        this.params = {
          id: data.id,
          assetCode: data.assetCode,
          code: data.code,
          name: data.name,
          brand: data.brand,
          areaCode: data.areaCode,
          allAreaName: data.allAreaName,
          type: data.type,
          typeText: data.typeText,
          productDate: data.productDate,
          description: data.description
        }
      }
    },
    uploadFile(e, index) {
      console.log(e, index)
      this.params.qualification[index].fileId = e[0].fileId
      this.params.qualification[index].fileName = e[0].fileName
    },
    // 获取字典
    async getDictionaryData() {
      const { code, data } = await getDepartment()
      if (code === '0') {
        this.genderList = data.content
      }
    },
    selectTime(index, type) {
      this.show = true
      this.active = 4
      this.targetTime = {
        index,
        type
      }
    },
    // 确定-时间
    submitTime() {
      this.show = false
      let formatTime = ParseDate(this.currentDate)
      this.params.productDate = formatTime
    },
    async toSelect(e) {
      this.active = e
      this.show = true

      if (e === 0) {
        const { code, data } = await getAreaList({
          parentAreaCode: '440900'
        })
        if (code === '0') {
          this.places = []
          data.forEach((item) => {
            this.places.push({
              text: item.areaName,
              value: item.areaCode
            })
          })
        }
      }
    },
    // 校验
    validate() {
      // 必填项-基本信息
      let requiredOfBase = [
        {
          label: '出厂编号',
          key: 'code'
        },
        {
          label: '设备名称',
          key: 'name'
        },
        {
          label: '品牌/厂家',
          key: 'brand'
        },
        {
          label: '所属区划',
          key: 'allAreaName'
        },
        {
          label: '设备类型',
          key: 'typeText'
        }
      ]

      try {
        requiredOfBase.forEach((item) => {
          let value = this.params[item.key].trim()
          if (value === '') {
            throw new Error(`${item.label} 为必填项！`)
          }
        })
        return true
      } catch (e) {
        this.$toast(e.message)
      }
    },
    // 提交
    async submit() {
      // 验证各字段是否为空
      if (!this.validate()) return false
      console.log(this.params)

      if (this.pageType === 'save') {
        console.log(this.params)
        this.params.qualificationJson = JSON.stringify(
          this.params.qualification
        )
        const { code } = await saveOrUpdateEquipment(this.params)
        if (code === '0') {
          this.$toast.success('提交成功')
          this.$router.go(-1)
        }
      } else {
        console.log(this.params)
        this.params.qualificationJson = JSON.stringify(
          this.params.qualification
        )
        const { code } = await saveOrUpdateEquipment(this.params)
        if (code === '0') {
          this.$toast.success('提交成功')
          this.$router.go(-1)
        }
      }
    },
    // 获取部门列表
    async getDepartment() {
      const { code, data } = await getDepartment()
      if (code === '0') {
        data.content.forEach((item) => {
          this.departments.push({
            text: item.departmentName,
            id: item.id
          })
        })
      }
    },
    // 确定类型
    confirmType() {
      let { value, text } = this.$refs.pickerForType.getValues()[0]
      this.show = false
      this.params.type = value
      this.params.typeText = text
    },
    // 检测区划改变
    async onChange({ value, selectedOptions, tabIndex }) {
      const { code, data } = await getAreaList({
        parentAreaCode: value
      })
      let placeIndex = ''
      let target = {}

      if (tabIndex > 0) {
        for (let i = 0; i <= tabIndex; i++) {
          if (selectedOptions[i].parentIndex !== undefined) {
            let parentIndex = selectedOptions[i].parentIndex
            console.log('parentIndex:', parentIndex)
            target = this.places[parentIndex].children
          }
        }
        placeIndex = target.findIndex((item) => item.value === value)
        target = target[placeIndex]
      } else {
        placeIndex = this.places.findIndex((item) => item.value === value)
        target = this.places[placeIndex]
      }

      if (code === '0') {
        data.forEach((item) => {
          if (tabIndex < 1) {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              children: [],
              parentIndex: placeIndex
            })
          } else {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              parentIndex: placeIndex
            })
          }
        })
      }
    },
    // 区划完成
    onFinish({ selectedOptions }) {
      this.params.allAreaName =
        selectedOptions.map((option) => option.text).join('') || ''
      // 获取区划码
      this.params.areaCode = selectedOptions[selectedOptions.length - 1].value
      console.log('finish')
      console.log(selectedOptions.map((option) => option.text).join('') || '')
      console.log(this.params.allAreaName)
      this.show = false
    }
  }
}
</script>

<style scoped lang="scss">
.btn_delete {
  text-align: center;
  color: rgba(255, 4, 4, 1);
  font-size: 14px;
}

// 暂无供货信息
.tip_add {
  text-align: center;
  margin: 10px 0;

  p {
    font-family: PingFang SC Regular;
    font-size: 14px;
    font-weight: normal;
    line-height: 19px;
    letter-spacing: 0px;
    /* 粤商通/常见灰色 */
    color: #b2b8bd;
    margin-bottom: 10px;
  }

  button {
    background: #2163e0;
    height: 28px;
    padding: 5px 15px;
    border-radius: 15px;
    color: #fff;
    font-family: PingFang SC Medium;
    font-size: 13px;
    font-weight: normal;
    line-height: 13px;
    letter-spacing: 0px;
  }

  .plus {
    font-size: 18px;
    font-weight: bolder;
    padding-right: 2px;
  }
}

// 附件
.attachment {
  .title {
    font-family: PingFang SC Regular;
    font-size: 14px;
    font-weight: normal;
    line-height: 19px;
    letter-spacing: 0px;
    /* 一级标题颜色 */
    color: #171819;
  }

  .tip {
    font-family: PingFang SC Regular;
    font-size: 14px;
    font-weight: normal;
    line-height: 19px;
    letter-spacing: 0px;
    /* 大灰 */
    color: #656c74;
  }

  .box {
    padding-top: 16px;
    padding-bottom: 14px;
    border-width: 0 0 0.5px 0;
    border-style: solid;
    border-color: #ebebeb;
  }
}
</style>
